<?php

class ServiceController extends MyClass_Action {
	protected $controller;
	protected $action;
	protected $_user;


	public function init() {

		$this->commonAction();	

	} 
	
	public function autoAction(){
		try {
/*			$d=strtotime("tomorrow");
			$tomorrow=date("Y-m-d");
*/			
			$day=date('Y-m-d');
			$sql="select * from chunyu_parents_total where from_unixtime(starttime,'%Y-%m-%d')='".$day."' and isopen=0 limit 10";   
			$parents=$this->_dbAdapter->fetchAll($sql);
			//print_r($parents);exit;
			
			foreach($parents as $key=>$value){
				//添加春雨账号
				$sql='select username,mobile from parents where pid='.$value['pid'];
				$resultparent = $this->_dbAdapter->fetchRow($sql);
				$username=$resultparent['username'];
				$mobile=$resultparent['mobile'];
				//print_r($resultparent);exit;
				$day=$value['month']*30;
				$time=time();
				$sign=md5($time.'_'.$username.'_'.'247c78y@328y2z89x948c');
	
				$data=array('user_id'=>$username,'phone'=>$mobile,'days'=>$day,'atime'=>$time,'sign'=>$sign);
				$data=http_build_query($data); 
				//print_r($data);exit;
				
				$opts=array('http'=>array('method'=>'POST', 'header'=>"Content-type:application/x-www-form-urlencoded\r\n". "Content-Length:".strlen($data)."\r\n",'content'=>$data)); 
				 $context=stream_context_create($opts);
				 $html=file_get_contents('http://yzxc.summer2.chunyu.me/partner/yzxc/create_vip',false,$context);
				 $p=json_decode($html);
				 //print_r($p->error);exit;
				 if($p->error==0){
			     	$result1=$this->_dbAdapter->update('chunyu_parents_total',array('isopen'=>1),'id='.$value['id']);
					if($result1){
						$data=array();
						$sql='select pid,endtime,isopen,month from chunyu_parents where pid='.$value['pid'];
						$pid=$this->_dbAdapter->fetchAll($sql);
						
						//pid存在且已到期，更新
						if($pid){
							$data=array(
								'isopen'=>1,
								'month'=>$pid[0]['month']+$value['month']
							);
							if($pid[0]['endtime']<strtotime(date('Y-m-d'))){
								$data['endtime']=strtotime(date('Y-m-d'))+$value['month']*30*86400;
							}else{
								$data['endtime']=$pid[0]['endtime']+$value['month']*30*86400;
							}
							$result=$this->_dbAdapter->update('chunyu_parents',$data,'pid='.$value['pid']);
						}else{//pid不存在
							$data=array(
								'pid'=>$value['pid'],
								'endtime'=>strtotime(date('Y-m-d'))+$value['month']*30*86400,
								'month'=>$value['month'],
								'isopen'=>1
							);
							$result=$this->_dbAdapter->insert('chunyu_parents',$data);
						}
					}
				 }else{
					$error=$p->error_msg;
					$sql='insert into chunyu_error (pid,err,date)values('.$value['pid'].',"'.$error.'","'.time().'")';
					$result=$this->_dbAdapter->query($sql);
				 }
			}
			
			$sql=" update chunyu_parents set isopen=0 where from_unixtime(endtime,'%Y-%m-%d')<'".$day."' and isopen=1 ";
			$result=$this->_dbAdapter->query($sql);
			exit;
			
		} catch ( Exception $e ) {
			echo $e->getMessage ();exit;
		}
	} 
	
	//查询学生列表	
	 public function indexAction() {
		try {  	
			$groupid = ( int ) $this->_request->getParam ( 'groupid' );
			$keyword = $this->_request->getParam ( 'keyword' );
			//print_r($groupid);print_r($keyword);exit;
			$where='';
			if ( $keyword){
				$where.=' and schoolname like "%'.$keyword.'%" ';
			}
			$where_group='';
			if ( $groupid){
				$where_group.=' and groupid ='.$groupid;
			}
			$this->view->groupid=$groupid;
			$this->view->keyword=$keyword;
			
			$sql="SELECT groupid,groupname FROM `groups` where 1 ".$where_group;
			$group=$this->_dbAdapter ->fetchPairs ( $sql );
			$this->view->group=$group;
			
            $count = 20;
			$curpage = ( int ) $this->_request->getParam ( 'page' );
	     	if (! $curpage)
    				$curpage = 1;
    		$offset = ($curpage - 1) * $count; 
			$sql="SELECT SQL_CALC_FOUND_ROWS schoolid,schoolname,groupid FROM `school` where 1 ".$where_group.$where ." limit $offset,$count";
			$school=$this->_dbAdapter ->fetchAssoc ( $sql );
    		$param ['file'] = '/' . $this->controller . '/' . $this->action;
    		$param ['totalnum'] = $this->_dbAdapter->fetchOne ( 'SELECT FOUND_ROWS()' ); 
    		$param ['perpagenum'] = $count; // 每页显示的数目
    		$param ['disnum'] = 11; // 取单数显示，当前页停在中间
    		$param ['curpage'] = $curpage; // 当前页码
			$this->view->allnum=$param ['totalnum'];

    		$page = new MyClass_Page ( $param );
    		$page->setvar (array());
			$this->view->page= $page->getNumPage (); 
			$schoolid=implode(',',array_keys($school));
			$sql='select a.*,b.productname from service_school_order a left join service_product b on a.productid=b.productid where a.schoolid in ('.$schoolid.')';
			$service=$this->_dbAdapter->fetchAll($sql);
			if($service)
			foreach($service as $key=>$value){
				if(in_array($value['schoolid'],array_keys($school))){
					$school[$value['schoolid']]['service'][]=$value;
				}
			}
			$this->view->school=$school;
			
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	   
	 public function addviewAction() {
		try { 
		    $sid = $this->_request->getParam ( 'sid' );  
		    $orderid = $this->_request->getParam ( 'orderid' ); 
	    
			if(empty($sid)){
				  throw new Exception ( '参数错误！' ); 
			} 
			if(empty($orderid)){
				  throw new Exception ( '参数错误！' ); 
			} 	
			$sql='select schoolname from school where schoolid='.$sid;
			$schoolname=$this->_dbAdapter->fetchOne($sql);
			$this->view->schoolname=$schoolname;
			
			$sql='select a.*,b.productname from service_school_order a left join service_product b on a.productid=b.productid where a.school_orderid='.$orderid;
			$order=$this->_dbAdapter->fetchRow($sql);
			$this->view->order=$order;
		
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	
	 public function opaddAction() {
		try { 
		    $num = $this->_request->getParam ( 'num' );  
		    $school_orderid = $this->_request->getParam ( 'school_orderid' );  
			if(empty($num)){
				  throw new Exception ( '参数错误！' ); 
			} 
			if(empty($school_orderid)){
				  throw new Exception ( '参数错误！' ); 
			} 	
			
		    $res=$this->_dbAdapter->update('service_school_order',array('studentnum'=>$num),"school_orderid=".$school_orderid);
		    if($res){
			  $this->feedback ( '成功', '注意', '/'.$this->controller.'/index', 'tip',0);		 
			}else{
			   $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
			}  
		
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	 public function buyviewAction() {
		try { 
		    $sid = $this->_request->getParam ( 'sid' );  
		    $gid = $this->_request->getParam ( 'gid' ); 
	    	
			if($sid){
				$this->view->school=$gid.'_'.$sid;
			}
			if($gid){
		     $this->view->groups=$gid; 
			}
			
			$sql='select productid,productname from service_product where 1';
			$product=$this->_dbAdapter->fetchPairs($sql);
			$this->view->product=$product;
		
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	
	 public function opbuyAction() {
		try { 
			if(! $this->isPost ()){
				throw new Exception ( '参数错误！' );
			}
			$p=$this->_request->getPost();
			//print_r($p);exit;
			if($p['school']){ 
				 $schoolarray=explode('_',$p['school']);  
				 $schoolid=$schoolarray['1'];
				 $groupid=$schoolarray['0'];
			}else{
				 throw new Exception ( '请选择学校！' );
			}
			if($p['chunyu']=='on'){
				if(!$p['month']){
					throw new Exception ( '请填月份！' );
				}
			}		

			$sql='select * from service_school_order where isdelete=0 and productid='.$p['productid'].' and schoolid='.$schoolid;
			$order=$this->_dbAdapter->fetchAssoc($sql);

			if($order){
				foreach($order as $key=>$value){
					$startime=strtotime($p['start_time']);
					if($startime<$value['end_time']){
						throw new Exception ( '服务期已存在！' );
					}
				}
			}
			$data=array(
				'schoolid'=>$schoolid,
				'productid'=>$p['productid'],
				'start_time'=>strtotime($p['start_time']),
				'end_time'=>strtotime($p['end_time']),
			);

			if($p['productid']==1){
				$data['studentnum']=$p['num'];
			}		
			if($p['chunyu']=='on'){
				$data['isopen_chunyu']=1;
				$data['month']=$p['month'];
			}		
		    $res=$this->_dbAdapter->Insert('service_school_order',$data);
		    if($res){
			  $this->feedback ( '成功', '注意', '/'.$this->controller.'/index/groupid/'.$groupid, 'tip',0);		 
			}else{
			   $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
			}  
		
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	 public function productlistAction() {
		try {  	
			$sql='select * from  service_product ';
			$service=$this->_dbAdapter->fetchAll($sql);
			$this->view->service=$service;
			
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	 public function addproductAction() {
		try { 

	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	 public function opaddproductAction() {
		try { 
			if(! $this->isPost ()){
				throw new Exception ( '参数错误！' );
			}
			$p=$this->_request->getPost();
			//print_r($p);exit;
			foreach($p as $key=>$value){
				$p[$key]=addslashes($value);
			}

			$sql="select * from service_product where productname='".$p['productname']."'";
			$product=$this->_dbAdapter->fetchAll($sql);

			if($product){
				throw new Exception ( '商品已存在！' );
			}
			$data=array(
				'productname'=>$p['productname'],
				'productdetail'=>$p['productdetail'],
			);

		    $res=$this->_dbAdapter->Insert('service_product',$data);
		    if($res){
			  $this->feedback ( '成功', '注意', '/'.$this->controller.'/productlist', 'tip',0);		 
			}else{
			   $this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
			}  
		
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
   public function groupsAction() {
		try { 
		 $p =$this->_request->getPost ();
         $sql="select * from  groups ";
	     $result = $this->_dbAdapter->fetchAll ($sql);
		 
		 $str.='<option value="0" >==请选择机构==</option>';
		 for($i = 0; $i<count($result); $i++)
		{
			$str .= "<option";
			if($p['jigouid']==$result[$i]['groupid']){
				$str .=" selected=selected ";
			}
	      $str .= " value='".$result[$i]['groupid']."'>".$result[$i]['groupname']."</option>";
		}
		  
	    echo $str;  exit;
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	//获取所有的校园列表
	  public function schoollistAction() {
		try { 
           if (! $this->isPost ()) {
					throw new Exception ( '参数错误！' );
			}			
		  $p =$this->_request->getPost (); 
		   
		  $array=explode('_',$p['sid']);
		  
		  $sql="SELECT * FROM `groups` where groupid='".$p['id']."' ";
		  $result = $this->_dbAdapter->fetchRow ($sql);
		    $sql="select * from  school where groupid='".$p['id']."' ";   
			$schoollist=$this->_dbAdapter->fetchAll ($sql);
	                 
            $str.='<option value="0" >==请选择学校==</option>';
			// echo $p['id'];   exit;
		 for($i = 0; $i<count($schoollist); $i++)
		{
		  $str .= "<option ";
		  
		  if ($array['1']==$schoollist[$i]['schoolid']){
		      $str .=" selected=selected";
		  }
		   $str .= " value='".$p['id'].'_'.$schoollist[$i]['schoolid']."'>";
		   $str .= $schoollist[$i]['schoolname']."</option>";
		   
		}
		   
	      echo $str;  exit;
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
	//获取所有的班级信息
	  public function classlistAction() {
		try { 
           if (! $this->isPost ()) {
					throw new Exception ( '参数错误！' );
			}			
		    $p =$this->_request->getPost ();  
		    $array=explode('_',$p['id']); 
			 
		    $sql="SELECT * FROM `groups` where groupid='".$array['0']."' ";
		    $result = $this->_dbAdapter->fetchRow ($sql);
	      
		  $sql="select * from  class  where isdel=0 and schoolid='".$array[1]."' ";   
		  $classlist= $this->_dbAdapter->fetchAll ($sql);
	      $str.='<option value="0" >==请选择班级==</option>';
		  	 
		 for($i = 0; $i<count($classlist); $i++)
		{
		  $str .= "<option ";
		  if($p['cid']==$classlist[$i]['classid']){
		     $str .=" selected=selected";
		  } 
		  $str .= "  value='".$classlist[$i]['classid']."'>".$classlist[$i]['classname']."</option>";
		    
		} 
		   
	      echo $str;  exit;
	} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'note', 'javascript:window.history.back();', 'warning' );
		}
	}
  /*
  操作处理end
  */	 
	 //以下内容保持不变
	public function noRouteAction() {
		$this->_redirect ( '/' );
	}
	
	public function __call($method, $args) {
		if ('Action' == substr ( $method, - 6 )) {
			$url = '/' . $this->controller . '/index';
			return $this->_redirect ( $url );
		}
		throw new Exception ( 'Invalid method' );
	}}

